package io.renren.modules.onlinestudy.service.impl;

import io.renren.common.config.FileServerConfig;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DfsUtil;
import io.renren.common.utils.FileServerResponse;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import io.renren.modules.onlinestudy.dao.QuestionDao;
import io.renren.modules.onlinestudy.entity.QuestionEntity;
import io.renren.modules.onlinestudy.service.QuestionService;



@Service("questionService")
public class QuestionServiceImpl implements QuestionService {
	@Autowired
	private QuestionDao questionDao;

	@Autowired
	private FileServerConfig fileServerConfig;
	
	@Override
	public QuestionEntity queryObject(String id){
		return questionDao.queryObject(id);
	}
	
	@Override
	public List<QuestionEntity> queryList(Map<String, Object> map){
		return questionDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return questionDao.queryTotal(map);
	}
	
	@Override
	public void save(QuestionEntity question) {
	    try {
            FileServerResponse response = DfsUtil.uploadFileByMultipartFile(question.getImageFile(), fileServerConfig.getImageUploadUrl());
            if (response.isSuccess()) {
                question.setImage("http://"+response.getHttpUrl());
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                question.setCreateTime(LocalDateTime.now().format(dateTimeFormatter));
                SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
                question.setCreateName(sysUserEntity.getUsername());
                questionDao.save(question);
            } else {
                throw new RRException(response.getMessage());
            }
        }catch (IOException e){
            throw new RRException(e.getMessage());
        }
	}
	
	@Override
	public void update(QuestionEntity question){
        try {
            if(!question.getImageFile().isEmpty()) {
                FileServerResponse response = DfsUtil.uploadFileByMultipartFile(question.getImageFile(), fileServerConfig.getImageUploadUrl());
                question.setImage("http://" + response.getHttpUrl());
            }
            questionDao.update(question);
        } catch (IOException e) {
            e.printStackTrace();
        }

	}
	
	@Override
	public void delete(String id){
		questionDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		questionDao.deleteBatch(ids);
	}
	
}
